const app = getApp();
Page({
  data: {
    routes: [],
    showRenameModal: false,
    customFileName: '',
    pendingFile: null,
    pendingOriginName: ''
  },
  onLoad() {
    this.getRoutes();
  },
  getRoutes() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/gpx/info/list`,
      method: 'GET',
      success: res => {
        if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
          const gpxList = res.data.data;
          const routes = [];
          let finished = 0;
          if (gpxList.length === 0) {
            this.setData({ routes: [] });
            return;
          }
          gpxList.forEach(info => {
            wx.request({
              url: `${app.globalData.baseUrl}/api/gpx/image/list/${info.id}`,
              method: 'GET',
              success: imgRes => {
                let coverImg = '';
                if (imgRes.data && imgRes.data.code === 200 && Array.isArray(imgRes.data.data) && imgRes.data.data.length > 0) {
                  const img = imgRes.data.data[0];
                  coverImg = img.filename ? `${app.globalData.baseUrl}/uploads/img/${img.filename}` : '';
                } else {
                  coverImg = '/images/default.jpg';
                }
                routes.push({
                  id: info.id,
                  fullName: info.filename,
                  displayName: info.roadName || info.displayName || '',
                  timeStr: info.startTime || '',
                  coverImg
                });
                finished++;
                if (finished === gpxList.length) {
                  this.setData({ routes });
                }
              },
              fail: () => {
                routes.push({
                  id: info.id,
                  fullName: info.filename,
                  displayName: info.roadName || info.displayName || '',
                  timeStr: info.startTime || '',
                  coverImg: '/images/default.jpg'
                });
                finished++;
                if (finished === gpxList.length) {
                  this.setData({ routes });
                }
              }
            });
          });
        }
      }
    });
  },
  chooseGpx() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['.gpx'],
      success: res => {
        const file = res.tempFiles[0];
        this.setData({
          showRenameModal: true,
          customFileName: file.name,
          pendingFile: file,
          pendingOriginName: file.name
        });
      }
    })
  },
  showRoute(e) {
    const idx = e.currentTarget.dataset.index;
    const route = this.data.routes[idx];
    wx.navigateTo({
      url: `/pages/gpxview/gpxview?id=${route.id}&edit=0`
    });
  },
  editRoute(e) {
    const idx = e.currentTarget.dataset.index;
    const route = this.data.routes[idx];
    wx.navigateTo({
      url: `/pages/gpxview/gpxview?id=${route.id}&edit=1`
    });
  },
  deleteRoute(e) {
    const filename = e.currentTarget.dataset.filename;
    wx.showModal({
      title: '确认删除',
      content: `确定要删除${filename}吗？`,
      success: res => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/gpx/delete/${filename}`,
            method: 'DELETE',
            success: () => {
              wx.showToast({ title: '已删除' });
              this.getRoutes();
            }
          })
        }
      }
    })
  },
  showRenameModal() {
    const oldName = this.data.pendingOriginName;
    this.setData({
      showRenameModal: true,
      customFileName: '',
      pendingOriginName: oldName
    });
  },
  onInputFileName(e) {
    this.setData({ customFileName: e.detail.value });
  },
  cancelRename() {
    this.setData({ showRenameModal: false, customFileName: '', pendingFile: null, pendingOriginName: '' });
  },
  confirmRename() {
    let customName = this.data.customFileName.trim();
    if (!customName) {
      customName = this.data.pendingOriginName;
    }
    if (!customName.endsWith('.gpx')) {
      customName += '.gpx';
    }
    const file = this.data.pendingFile;
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/api/gpx/upload`,
      filePath: file.path,
      name: 'file',
      formData: {
        filename: customName
      },
      success: uploadRes => {
        wx.showToast({ title: '上传成功' });
        let filename = '', displayName = '', fileSize = '';
        try {
          const resObj = JSON.parse(uploadRes.data);
          if (resObj.code === 200 && resObj.data) {
            filename = resObj.data.filename || '';
            displayName = resObj.data.displayName || '';
            fileSize = resObj.data.fileSize || '';
          }
        } catch (e) {}
        this.setData({ showRenameModal: false, customFileName: '', pendingFile: null, pendingOriginName: '' });
        if (filename) {
          wx.redirectTo({
            url: `/pages/map/map?filename=${encodeURIComponent(filename)}&display_name=${encodeURIComponent(displayName)}&file_size=${encodeURIComponent(fileSize)}`
          });
        }
      },
      fail: err => {
        wx.showToast({ title: '上传失败', icon: 'none' });
        this.setData({ showRenameModal: false, customFileName: '', pendingFile: null, pendingOriginName: '' });
      }
    });
  },
  formatFileName(name) {
    if (!name) return '';
    if (name.length <= 20) return name;
    return name.slice(0, 8) + '...' + name.slice(-8);
  },
  onView(e) {
    // 兼容原有 showRoute
    const id = e.currentTarget.dataset.id;
    if (this.showRoute) {
      this.showRoute({ currentTarget: { dataset: { id } } });
    }
  },
  onEdit(e) {
    // 兼容原有 editRoute
    const id = e.currentTarget.dataset.id;
    if (this.editRoute) {
      this.editRoute({ currentTarget: { dataset: { id } } });
    }
  },
  onDelete(e) {
    // 兼容原有 deleteRoute
    const id = e.currentTarget.dataset.id;
    if (this.deleteRoute) {
      this.deleteRoute({ currentTarget: { dataset: { id } } });
    }
  },
  onUploadGpx() {
    // 兼容原有 chooseGpx
    if (this.chooseGpx) {
      this.chooseGpx();
    }
  }
}) 